'use strict';

var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };

// gen一个随机数值串出来
function genRandCode(leng) {
  if (String(typeof leng === 'undefined' ? 'undefined' : _typeof(leng)).toLocaleLowerCase() === 'number') return Math.random().toFixed(leng).toString().replace(/\d\./, '');else {
    throw new Error('\u6536\u5230\u7C7B\u578B\u4E0D\u4E3A\u6570\u503C\u7684\u53C2\u6570\uFF1A' + leng + ' | ' + String(typeof leng === 'undefined' ? 'undefined' : _typeof(leng)).toLocaleLowerCase() + '\u3002\u65E0\u6CD5\u4EA7\u751F\u6307\u5B9A\u957F\u5EA6\u968F\u673A\u6570');
  }
}
// gen一个随机字母串出来
function genRandEngCode(leng) {
  var result = '';
  var i = 0;
  var tempArr = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
  if (String(typeof leng === 'undefined' ? 'undefined' : _typeof(leng)).toLocaleLowerCase() === 'number') {
    while (i < leng) {
      var randomNum = ~~(Math.random() * 26);
      result += tempArr[randomNum];
      i++;
    }
    return result;
  } else {
    throw new Error('\u6536\u5230\u7C7B\u578B\u4E0D\u4E3A\u6570\u503C\u7684\u53C2\u6570\uFF1A' + leng + ' | ' + String(typeof leng === 'undefined' ? 'undefined' : _typeof(leng)).toLocaleLowerCase() + '\u3002\u65E0\u6CD5\u4EA7\u751F\u6307\u5B9A\u957F\u5EA6\u968F\u673A\u6570');
  }
}
/**
 * 截取指定长度的数值字符串
 * @param {string|number} num 要截取的数字基础
 * @param {number} leng 截取长度
 * @return {string} 返回指定长度的数值字符串
 */
function addPreZero(num, leng) {
  var tempStr = '';
  var i = 0;
  while (i < leng) {
    tempStr += '0';
    i++;
  }
  return ('' + tempStr + num).slice(-leng);
}

/**
 * 组装符合后端要求的数据结构并parse为表单项进行表单提交
 * @param {HTMLElement} _this 触发当前函数的HTML元素
 * @param {number} nameBase 根据后端要求，数组是以数字为键，客户要求为6， 按揭要求是7
 * @param {string} formID 要进行提交的form表单id，将按照id选取元素进行序列化后做进一步处理
 */
function postThisSubPage(_this, nameBase, formID) {
  var formValue = [];
  var formAction = $('#' + formID).attr('action');
  var tempNameArr = [];
  var tempValueObj = {};
  var tempForm = '<form autocomplete="off" method=\'post\' action=\'' + formAction + '\' id=\'tempGenForm\'></form>';
  var tempInput = '';
  var PreValue = JSON.parse('[]');
  try {
    PreValue = JSON.parse(sessionStorage.getItem('nextPingu'));
  } catch (err) {
    console.log('\u89E3\u6790\u6570\u636E\u53D1\u751F\u9519\u8BEF\uFF1A');
    console.log(sessionStorage.getItem('nextPingu'));
    $.toptip('历史数据解析发生错误，请联系工作人员', 'error');
    throw new Error(err);
  }
  var _iteratorNormalCompletion = true;
  var _didIteratorError = false;
  var _iteratorError = undefined;

  try {
    for (var _iterator = PreValue[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
      var item = _step.value;

      tempInput += '<input type=\'hidden\' name=\'' + item.name + '\' value=\'' + item.value + '\'>';
    }
  } catch (err) {
    _didIteratorError = true;
    _iteratorError = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion && _iterator.return) {
        _iterator.return();
      }
    } finally {
      if (_didIteratorError) {
        throw _iteratorError;
      }
    }
  }

  if (String(nameBase) === '9') {
    formValue = [[
      // {
      //   zhengxin_check_count_method: '',
      //   zhengxin_check_count_cycle: '',
      //   zhengxin_check_count_time: ''
      // }
    ], [
      // {
      //   yuqi_check_count_cycle: '',
      //   yuqi_check_count_method: '',// 累计
      //   yuqi_check_count_time: '',
      //   yuqi_check_count_source: ''
      // }
    ]];
    // 9 是特殊情况，需要数组套数组
    /**
     * // 征信
     * $arr[9][0]=array(
     *   0=>array(
     *     //'zhengxin_check_if'=>'',
     *     'zhengxin_check_count_method'=>'信用卡查询',
     *     'zhengxin_check_count_cycle'=>'2',
     *     'zhengxin_check_count_time'=>'9'
     *   ),
     *   1=>array(
     *    // 'zhengxin_check_if'=>'',
     *     'zhengxin_check_count_method'=>'信用卡查询',
     *     'zhengxin_check_count_cycle'=>'3',
     *     'zhengxin_check_count_time'=>'1'
     *   ),
     *   1=>array(
     *     //'zhengxin_check_if'=>'',
     *     'zhengxin_check_count_method'=>'信用卡查询',
     *     'zhengxin_check_count_cycle'=>'6',
     *     'zhengxin_check_count_time'=>'6'
     *   ),
     * )
     * // 逾期
     * $arr[9][1]=array(...)
     */
    /** 首先是征信数据处理，name 处理为形如 [0][n][zhengxin_check_count_method] */
    // 判断是否需要提交，判断点击和按钮是否多余0
    var count = $('#zhengxin_popup .tag_wrap input:checked').length;
    var zhengxinMethod = [];
    if (count > 0) {
      // 循环多选按钮
      $('.zhengxin_block .tag_container [name=\'zhengxin_fliter\']').each(function (index, item) {
        zhengxinMethod.push($(item).val());
      });
      zhengxinMethod = zhengxinMethod.join(',');
      // 循环每一个fliter行
      $('.zhengxin_block .fliter_line').each(function (index, item) {
        var cycle = $(item).find('input[name=\'zhengxin_check_count_cycle\']').attr('inori-data-code');
        var time = $(item).find('input[name=\'zhengxin_check_count_time\']').attr('inori-data-code');
        formValue[0][index] = {};
        formValue[0][index].zhengxin_check_count_method = zhengxinMethod;
        formValue[0][index].zhengxin_check_count_cycle = cycle;
        formValue[0][index].zhengxin_check_count_time = time;
      });
    }
    /** 然后是逾期数据处理，name 处理为形如 [1][n][yuqi_check_count_cycle] */
    $('.yuqi_block .fliter_line').each(function (index, item) {
      var cycle = $(item).find('input[name=\'yuqi_check_count_cycle\']').attr('inori-data-code');
      var time = $(item).find('input[name=\'yuqi_check_count_time\']').attr('inori-data-code');
      var source = $(item).find('input[name=\'yuqi_check_count_source\']').attr('inori-data-code');
      formValue[1][index] = {};
      formValue[1][index].yuqi_check_count_cycle = cycle;
      formValue[1][index].yuqi_check_count_method = '累计';
      formValue[1][index].yuqi_check_count_time = time;
      formValue[1][index].yuqi_check_count_source = source;
    });
    // 生成模板内容
    // for (let item of Object.keys(tempValueObj)) {
    //   let value = tempValueObj[item]
    //   let name = item
    //   tempInput += `<input type='hidden' name='${nameBase}${name}' value='${value}'>`
    // }
    $.each(formValue, function (zhengxinOryuqi, dataArray) {
      $.each(dataArray, function (index, dataObject) {
        $.each(dataObject, function (name, value) {
          tempInput += '<input type=\'hidden\' name=\'' + nameBase + '[' + zhengxinOryuqi + '][' + index + '][' + name + ']\' value=\'' + value + '\'>';
        });
      });
    });
  } else {
    formValue = $('#' + formID).serializeArray();
    $.each(formValue, function (index, item) {
      if (tempNameArr.indexOf(item.name) === -1) {
        tempNameArr.push(item.name);
        tempValueObj[item.name] = '' + item.value;
      } else {
        tempValueObj[item.name] += ',' + item.value;
      }
    });
    var _iteratorNormalCompletion2 = true;
    var _didIteratorError2 = false;
    var _iteratorError2 = undefined;

    try {
      for (var _iterator2 = Object.keys(tempValueObj)[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
        var _item = _step2.value;

        var value = tempValueObj[_item];
        var name = _item;
        tempInput += '<input type=\'hidden\' name=\'' + nameBase + '[' + name + ']\' value=\'' + value + '\'>';
      }
    } catch (err) {
      _didIteratorError2 = true;
      _iteratorError2 = err;
    } finally {
      try {
        if (!_iteratorNormalCompletion2 && _iterator2.return) {
          _iterator2.return();
        }
      } finally {
        if (_didIteratorError2) {
          throw _iteratorError2;
        }
      }
    }
  }

  // 提交之前刷新一次session
  sessionStorage.setItem('currentFilter', 'null');
  window.top.postMessage({ formData: tempForm.replace('></form>', '>' + tempInput + '</form>') }, '*');
  // // console.log(`${tempInput}`)
  // if ($('#tempGenForm')) $('#tempGenForm').remove()
  // $('body').append(tempForm)
  // $('#tempGenForm').append(tempInput)
  // // throw new Error('debug')
  // $('#tempGenForm').submit()
}

function postOrder(evt) {
  $.toptip('正在重组数据', 'success');
  var PreValue = JSON.parse('[]');
  var value = $(evt.target).text().charCodeAt(0) === 59045 ? 1 : 0;
  var formAction = $('#order_query').val();
  var tempForm = '<form autocomplete="off" method=\'post\' action=\'' + formAction + '\' id=\'tempGenForm\'></form>';
  var tempInput = '';
  var sessionValue = evt.data.type === 'lx' ? function () {
    return $('#lixi_sort').text().charCodeAt(0) === 59045 ? [1, 0] : [0, 0];
  }() : function () {
    return $('#edu_sort').text().charCodeAt(0) === 59045 ? [0, 1] : [0, 0];
  }();
  try {
    PreValue = JSON.parse(sessionStorage.getItem('nextPingu'));
  } catch (err) {
    console.log('\u89E3\u6790\u6570\u636E\u53D1\u751F\u9519\u8BEF\uFF1A');
    console.log(sessionStorage.getItem('nextPingu'));
    $.toptip('历史数据解析发生错误，请联系工作人员', 'error');
    throw new Error(err);
  }
  sessionStorage.setItem('lastProduct_sort_arr', JSON.stringify(sessionValue));
  var _iteratorNormalCompletion3 = true;
  var _didIteratorError3 = false;
  var _iteratorError3 = undefined;

  try {
    for (var _iterator3 = PreValue[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
      var item = _step3.value;

      tempInput += '<input type=\'hidden\' name=\'' + item.name + '\' value=\'' + item.value + '\'>';
    }
  } catch (err) {
    _didIteratorError3 = true;
    _iteratorError3 = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion3 && _iterator3.return) {
        _iterator3.return();
      }
    } finally {
      if (_didIteratorError3) {
        throw _iteratorError3;
      }
    }
  }

  tempInput += '<input type=\'hidden\' name=\'5[0]\' value=\'' + value + '\'>';
  tempInput += '<input type=\'hidden\' name=\'5[1]\' value=\'' + evt.data.type + '\'>';

  // if ($('#tempGenForm')) $('#tempGenForm').remove()
  // $('body').append(tempForm)
  // $('#tempGenForm').append(tempInput)
  // throw new Error('debug')
  $.toptip('正在发送请求', 'success');
  window.top.postMessage({ formData: tempForm.replace('></form>', '>' + tempInput + '</form>') }, '*');
  // $('#tempGenForm').submit()
}

// 生成uid
$('.pro_uid').each(function (index, item) {
  var leng = 5;
  var rawID = '';
  if ($(item).attr('inori-data')) rawID = $(item).attr('inori-data').replace(/\D/g, '');else {
    return;
  }
  var resultID = '';
  var rawIDAlt = addPreZero(rawID, leng);
  resultID = 'A' + genRandEngCode(1) + genRandCode(1) + rawIDAlt.substr(0, 4) + genRandCode(2) + rawIDAlt.substr(-1);
  $(item).text(resultID);
  sessionStorage.setItem('pro_id' + rawID, resultID);
  // console.log(rawID)
});

/**
 * 发送后端一个ajax请求
 * @param {event} evt 点击事件
 */
// function postThisQudaoID (evt) {
//   let qudaoID = $(evt.target).attr('qudao-id')
//   let urlEleID = ''
//   let ajaxMethod = ''
//   let urlBase = ''
//   if (evt.data) {
//     urlEleID = evt.data.urlEleID || 'add_qudao_to_chat_room'
//     ajaxMethod = evt.data.method || 'post'
//   }
//   urlBase = $(`#${urlEleID}`).val() === '' ? (() => { throw new Error(`ajax 取值为空`) })() : String($(`#${urlEleID}`).val())
//   console.log(`发送ajax请求，地址： ${urlBase}，数据：{qudaoID: ${qudaoID}}， method：${ajaxMethod}`)
//   $.ajax(urlBase, {
//     method: ajaxMethod,
//     data: {qudaoID: qudaoID}
//   }).done((data) => {
//     console.log('接收数据：')
//     console.log(data)
//   }).fail((err) => {
//     console.log('返回错误：')
//     console.log(err)
//   })
// }

// 监听聊天按钮点击
// $('.contact_button').on({click: postThisQudaoID}, {urlEleID: '', method: 'post'})
// 监听列表按钮点击
$('.pro_adv .weui-btn_mini').each(function (index, item) {
  $(item).on('touchstart', function (evt) {
    evt.preventDefault();
    evt.stopPropagation();
    var eleID = $(evt.target).attr('for');
    if ($('#' + eleID).prop('checked') && $(evt.target).attr('confirmed') === 'true') {
      // 已经激活，需要关闭本页并移除本active
      $('#' + eleID).prop('checked', false).change();
      $(evt.target).removeClass('active');
    } else {
      // 未激活
      // 筛选列表地下渠道是否已经在聊天室
      var from_user_group_id = sessionStorage.getItem('from_user_group_id');
      if (from_user_group_id === null || from_user_group_id === 'null') {
        // 激活本页并移除其他active
        $('#' + eleID).prop('checked', true).change();
        $('.pro_adv .weui-btn_mini').each(function (index, item) {
          if ($(item).hasClass('active')) $(item).removeClass('active');
        });
        $(evt.target).addClass('active');
        return;
      } else if ($(evt.target).attr('confirmed') === 'true') {
        // 激活本页并移除其他active
        $('#' + eleID).prop('checked', true).change();
        $('.pro_adv .weui-btn_mini').each(function (index, item) {
          if ($(item).hasClass('active')) $(item).removeClass('active');
        });
        $(evt.target).addClass('active');
        return;
      } else {
        // 正在筛选,不做任何事情直接返回
        if ($(evt.target).attr('confirmed') === 'doing') return;
        // 进行筛选
        $(evt.target).attr('confirmed', 'doing');
        var ajaxIfURL = String($('#ajax_jud').val());
        var roomID = String($('#chat_person_id').val());
        // 筛选promise数组
        var checkPromiseArr = [];
        var targetContainerEle = $('#' + $(evt.target).attr('for')).closest('.pro_qudao');
        $.each(targetContainerEle.find('.contact_button[goods-id][qudao-id]'), function (index, item) {
          if ($(item).attr('checking') === 'done') {
            return;
          }
          var qudaoID = String($(item).attr('qudao-id'));
          var goodsID = String($(item).attr('goods-id'));
          var ajaxAddData = {
            chat_id: roomID,
            goods_id: goodsID,
            y_id: qudaoID
            // 待筛选按钮
          };checkPromiseArr.push(new Promise(function (resolve, reject) {
            $.ajax(ajaxIfURL, {
              method: 'post',
              data: ajaxAddData,
              beforeSend: function beforeSend() {
                $(item).attr('checking', 'true');
              }
            }).fail(function (err) {
              resolve();
              $(item).attr('checking', 'done');
            }).done(function (res) {
              resolve();
              $(item).attr('checking', 'done');
              if (String(res.code) === '1') {
                $(item).text('正在互动');
                $(item).removeAttr('onclick');
                $(item).off('click');
                $(item).on('click', function (evt) {
                  $.toptip('\u8BE5\u6E20\u9053\u5DF2\u7ECF\u5728\u7559\u8A00\u677F\u4E86', 'warning');
                  evt.preventDefault();
                });
              }
            });
          }));
        });
        if (checkPromiseArr.length === 0) {
          // 检查对象长度为0
          $(evt.target).attr('confirmed', 'true');
          // 激活本页并移除其他active
          $('#' + eleID).prop('checked', true).change();
          $('.pro_adv .weui-btn_mini').each(function (index, item) {
            if ($(item).hasClass('active')) $(item).removeClass('active');
          });
          $(evt.target).addClass('active');
          return;
        }
        $.toptip('正在查询渠道情况，列表即将渲染。请稍候。。。', 900, 'success');
        Promise.all(checkPromiseArr).then(function (_) {
          $(evt.target).attr('confirmed', 'true');
          // 激活本页并移除其他active
          $('#' + eleID).prop('checked', true).change();
          $('.pro_adv .weui-btn_mini').each(function (index, item) {
            if ($(item).hasClass('active')) $(item).removeClass('active');
          });
          $(evt.target).addClass('active');
        }).catch(function (err) {
          $(evt.target).attr('confirmed', 'true');
          // 激活本页并移除其他active
          $('#' + eleID).prop('checked', true).change();
          $('.pro_adv .weui-btn_mini').each(function (index, item) {
            if ($(item).hasClass('active')) $(item).removeClass('active');
          });
          $(evt.target).addClass('active');
        });
      }
    }
  });
});

// 修改并列出"客户要求"区域的title对应nama
$(document).ready(function () {
  $('.tag_title[inori-title-data]').each(function (index, item) {
    var titleDataArr = $(item).attr('inori-title-data').split(',');
    var title = titleDataArr[0];
    var titleName = titleDataArr[1];
    $(item).text(title.replace(/标签/, '').replace(/维度/, '').replace(/纬度/, ''));
    $(item).closest('.weui_cells').find('input').each(function (index, item) {
      $(item).attr('name', titleName);
    });
  });
  // 监听排序
  $('#lixi_sort').on({ click: postOrder }, { type: 'lx' });
  $('#edu_sort').on({ click: postOrder }, { type: 'ed' });

  // 如果存在筛选条件，那么添加一个重置按钮
  if (sessionStorage.getItem('currentFilter')) {
    try {
      var filter = JSON.parse(sessionStorage.getItem('currentFilter'));
      // if (filter.length > 6) {
      //   // 长度大于6代表是有筛选操作
      //   $('.js-loadmore span').text(`重置`)
      //   $('.js-loadmore').one('click', evt => {
      //     $('#lixi_sort').click()
      //   })
      // }
      var shouldHaveReaset = false;
      $.each(filter, function (index, item) {
        // 大于6代表是有筛选操作
        if (Number.parseInt(item.name.substr(0, 1)) >= 6) {
          shouldHaveReaset = true;
        }
      });
      if (shouldHaveReaset) {
        var templ = '\n          <div class="weui-loadmore weui-loadmore_line js-loadmore">\n            <!-- \u8DDF\u968Fbody\u80CC\u666F\u8272 -->\n            <span class="weui-loadmore__tips" style=\'background-color:#eaeff5;\'>\u70B9\u6211\u91CD\u7F6E\u6761\u4EF6</span>\n          </div>\n        ';
        $('#rewriteTag_container').after(templ);
        var reFliting = false;
        $('.js-loadmore').on('click', function (evt) {
          if (reFliting) {
            $.toptip('正在重组数据', 'success');
            evt.preventDefault();
            return;
          }
          // $('#lixi_sort').click()
          $.toptip('正在重组数据', 'success');
          reFliting = true;
          var PreValue = JSON.parse('[]');
          var formAction = $('#order_query').val();
          var tempForm = '<form autocomplete="off" method=\'post\' action=\'' + formAction + '\' id=\'tempGenForm\'></form>';
          var tempInput = '';
          try {
            PreValue = JSON.parse(sessionStorage.getItem('nextPingu'));
          } catch (err) {
            console.log('\u89E3\u6790\u6570\u636E\u53D1\u751F\u9519\u8BEF\uFF1A');
            console.log(sessionStorage.getItem('nextPingu'));
            $.toptip('历史数据解析发生错误，请联系工作人员', 'error');
            throw new Error(err);
          }
          var _iteratorNormalCompletion4 = true;
          var _didIteratorError4 = false;
          var _iteratorError4 = undefined;

          try {
            for (var _iterator4 = PreValue[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
              var item = _step4.value;

              tempInput += '<input type=\'hidden\' name=\'' + item.name + '\' value=\'' + item.value + '\'>';
            }

            // if ($('#tempGenForm')) $('#tempGenForm').remove()
            // $('body').append(tempForm)
            // $('#tempGenForm').append(tempInput)
            // throw new Error('debug')
          } catch (err) {
            _didIteratorError4 = true;
            _iteratorError4 = err;
          } finally {
            try {
              if (!_iteratorNormalCompletion4 && _iterator4.return) {
                _iterator4.return();
              }
            } finally {
              if (_didIteratorError4) {
                throw _iteratorError4;
              }
            }
          }

          sessionStorage.setItem('lastProduct_sort_arr', '[0, 0]');
          $.toptip('正在发送请求', 'success');
          window.top.postMessage({ formData: tempForm.replace('></form>', '>' + tempInput + '</form>') }, '*');
          reFliting = false;
        });
      }
    } catch (e) {
      // 解析失败
      console.groupCollapsed(new Date() + ' \u89E3\u6790\u7B5B\u9009\u6570\u636E\u5931\u8D25');
      console.error(e);
      console.groupEnd();
    }
  }
});
// 初始化征信查询卡片查询
var mouthArray = Array(36);
var mouthViewArray = Array(36);
var countTimeArray = Array(20);
var countTimeViewArray = Array(20);
$.each(mouthArray, function (index, item) {
  mouthArray[index] = index + 1;
  if (index < 35) mouthViewArray[index] = index + 1 + '\u4E2A';else mouthViewArray[index] = index + 1 + '\u4E2A';
});
$.each(countTimeArray, function (index, item) {
  countTimeArray[index] = index + 1;
  if (index < 19) countTimeViewArray[index] = index + 1 + '\u6B21';else countTimeViewArray[index] = index + 1 + '\u6B21\u6216\u4EE5\u4E0A';
});

$('.zhengxin_check_count_cycle_wrap input').picker({
  title: "计算周期",
  cols: [{
    textAlign: 'center',
    values: mouthArray,
    displayValues: mouthViewArray
  }],
  onChange: function onChange(picker, values, displayValues) {
    picker.input.attr('inori-data-code', values[0]);
    setTimeout(function () {
      picker.input.val(displayValues[0]);
    }, 0);
  }
});
$(".zhengxin_check_count_cycle_wrap input").picker("open");
$(".zhengxin_check_count_cycle_wrap input").picker("close");

$('.zhengxin_check_count_time_wrap input').picker({
  title: "不超过",
  cols: [{
    textAlign: 'center',
    values: countTimeArray,
    displayValues: countTimeViewArray
  }],
  onChange: function onChange(picker, values, displayValues) {
    picker.input.attr('inori-data-code', values[0]);
    setTimeout(function () {
      picker.input.val(displayValues[0]);
    }, 0);
  }
});
$(".zhengxin_check_count_time_wrap input").picker("open");
$(".zhengxin_check_count_time_wrap input").picker("close");

// 初始化逾期查询卡片查询
// 变量定义
/** 12 */
var yuqiCheckCountCycleArray = Array(12);
/** 12 */
var yuqiCheckCountCycleViewArray = Array(12);
/** 10 */
var yuqiCheckCountTimeArray = Array(10);
/** 10个或以上 */
var yuqiCheckCountTimeViewArray = Array(10);
/** 12 */
var yuqiCheckCountSourceArray = Array(12);
/** 12 */
var yuqiCheckCountSourceViewArray = Array(12);
$.each(yuqiCheckCountCycleArray, function (index, item) {
  yuqiCheckCountCycleArray[index] = index + 1;
  if (index < 11) yuqiCheckCountCycleViewArray[index] = index + 1 + '\u4E2A';else yuqiCheckCountCycleViewArray[index] = index + 1 + '\u4E2A';
});
$.each(yuqiCheckCountTimeArray, function (index, item) {
  yuqiCheckCountTimeArray[index] = index + 1;
  if (index < 9) yuqiCheckCountTimeViewArray[index] = index + 1 + '\u4E2A';else yuqiCheckCountTimeViewArray[index] = index + 1 + '\u4E2A\u6216\u4EE5\u4E0A';
});
$.each(yuqiCheckCountSourceArray, function (index, item) {
  yuqiCheckCountSourceArray[index] = index + 1;
  if (index < 11) yuqiCheckCountSourceViewArray[index] = '' + (index + 1);else yuqiCheckCountSourceViewArray[index] = '' + (index + 1);
});
// 全局挂载
window.zhengxinDataArray = {
  mouthArray: mouthArray,
  mouthViewArray: mouthViewArray,
  countTimeArray: countTimeArray,
  countTimeViewArray: countTimeViewArray,
  yuqiCheckCountCycleArray: yuqiCheckCountCycleArray,
  yuqiCheckCountCycleViewArray: yuqiCheckCountCycleViewArray,
  yuqiCheckCountTimeArray: yuqiCheckCountTimeArray,
  yuqiCheckCountTimeViewArray: yuqiCheckCountTimeViewArray,
  yuqiCheckCountSourceArray: yuqiCheckCountSourceArray,
  yuqiCheckCountSourceViewArray: yuqiCheckCountSourceViewArray
};
$('.yuqi_check_count_cycle_wrap input').picker({
  title: "N个月",
  cols: [{
    textAlign: 'center',
    values: yuqiCheckCountCycleArray,
    displayValues: yuqiCheckCountCycleViewArray
  }],
  onChange: function onChange(picker, values, displayValues) {
    picker.input.attr('inori-data-code', values[0]);
    setTimeout(function () {
      picker.input.val(displayValues[0]);
    }, 0);
  }
});
$(".yuqi_check_count_cycle_wrap input").picker("open");
$(".yuqi_check_count_cycle_wrap input").picker("close");

$('.yuqi_check_count_time_wrap input').picker({
  title: "N个",
  cols: [{
    textAlign: 'center',
    values: yuqiCheckCountTimeArray,
    displayValues: yuqiCheckCountTimeViewArray
  }],
  onChange: function onChange(picker, values, displayValues) {
    picker.input.attr('inori-data-code', values[0]);
    setTimeout(function () {
      picker.input.val(displayValues[0]);
    }, 0);
  }
});
$(".yuqi_check_count_time_wrap input").picker("open");
$(".yuqi_check_count_time_wrap input").picker("close");

$('.yuqi_check_count_source_wrap input').picker({
  title: "N",
  cols: [{
    textAlign: 'center',
    values: yuqiCheckCountSourceArray,
    displayValues: yuqiCheckCountSourceViewArray
  }],
  onChange: function onChange(picker, values, displayValues) {
    picker.input.attr('inori-data-code', values[0]);
    setTimeout(function () {
      picker.input.val(displayValues[0]);
    }, 0);
  }
});
$(".yuqi_check_count_source_wrap input").picker("open");
$(".yuqi_check_count_source_wrap input").picker("close");

// 只有选了才会有
$('#zhengxin_popup .tag_wrap input').on('change', function (evt) {
  var count = $('#zhengxin_popup .tag_wrap input:checked').length;
  if (count > 0) {
    $(evt.target).closest('.weui_cells').find('.fliter_line').each(function (index, item) {
      $(item).css('display', 'flex');
    });
  } else {
    $(evt.target).closest('.weui_cells').find('.fliter_line').each(function (index, item) {
      $(item).css('display', 'none');
    });
  }
});
// 开局click一下，隐藏
$('#zhengxin_popup .tag_wrap input:eq(0)').change();
// 动态添加征信筛选条件
$('#click_to_add_zhengxin').on('click', function (evt) {
  var parentEle = $(evt.target).closest('.fliter_line');
  var imgURL = parentEle.attr('imgurl');
  // 自增才能下一步
  var countNum = Number(parentEle.attr('inori-count')) + 1;
  if (countNum > 7) {
    $.toptip('\u6BCF\u7C7B\u6761\u4EF6\u6700\u591A\u53EF\u4EE5\u6DFB\u52A07\u6761');
    throw new Error('\u6BCF\u7C7B\u6761\u4EF6\u6700\u591A\u53EF\u4EE5\u6DFB\u52A07\u6761');
  }
  parentEle.attr('inori-count', countNum);
  var templ = ('\n    <div class="fliter_line">\n      <div class="zhengxin_check_count_cycle_wrap"><input form=\'hidden_form_shaixuan\' type="text" name="zhengxin_check_count_cycle" id="zhengxin_check_count_cycle_' + countNum + '"></div>\n      <div class="zhengxin_popup_placeholder">\u6708\u5185\u67E5\u8BE2</div>\n      <div class="zhengxin_check_count_time_wrap"><input form=\'hidden_form_shaixuan\' type="text" name="zhengxin_check_count_time" id="zhengxin_check_count_time_' + countNum + '"></div>\n      <div class="click_to_delete" onclick=\'deleteThisFliterLine(this, event)\'>-<img src="' + imgURL + '" alt="u1490"></div>\n    </div>\n    <script>\n      $(\'#zhengxin_check_count_cycle_' + countNum + '\').picker({\n        title: "\u8BA1\u7B97\u5468\u671F",\n        cols: [\n          {\n            textAlign: \'center\',\n            values: window.zhengxinDataArray.mouthArray,\n            displayValues: window.zhengxinDataArray.mouthViewArray\n          }\n        ],\n        onChange: (picker, values, displayValues) => {\n          picker.input.attr(\'inori-data-code\', values[0])\n          setTimeout(()=>{picker.input.val(displayValues[0])}, 0)\n        }\n      })\n      $("#zhengxin_check_count_cycle_' + countNum + '").picker("open")\n      $("#zhengxin_check_count_cycle_' + countNum + '").picker("close")\n      $(\'#zhengxin_check_count_time_' + countNum + '\').picker({\n        title: "\u4E0D\u8D85\u8FC7",\n        cols: [\n          {\n            textAlign: \'center\',\n            values: window.zhengxinDataArray.countTimeArray,\n            displayValues: window.zhengxinDataArray.countTimeViewArray\n          }\n        ],\n        onChange: (picker, values, displayValues) => {\n          picker.input.attr(\'inori-data-code\', values[0])\n          setTimeout(()=>{picker.input.val(displayValues[0])}, 0)\n        }\n      })\n      $("#zhengxin_check_count_time_' + countNum + '").picker("open")\n      $("#zhengxin_check_count_time_' + countNum + '").picker("close")\n    </script>\n  ').trim();
  parentEle.closest('.weui_cells').append(templ);
});
// 动态添加逾期筛选条件
$('#click_to_add_yuqi').on('click', function (evt) {
  var parentEle = $(evt.target).closest('.fliter_line');
  var imgURL = parentEle.attr('imgurl');
  // 自增才能下一步
  var countNum = Number(parentEle.attr('inori-count')) + 1;
  if (countNum > 7) {
    $.toptip('\u6BCF\u7C7B\u6761\u4EF6\u6700\u591A\u53EF\u4EE5\u6DFB\u52A07\u6761');
    throw new Error('\u6BCF\u7C7B\u6761\u4EF6\u6700\u591A\u53EF\u4EE5\u6DFB\u52A07\u6761');
  }
  parentEle.attr('inori-count', countNum);
  var templ = ('\n    <div class="fliter_line">\n      <div class="yuqi_check_count_cycle_wrap"><input form=\'hidden_form_shaixuan\' type="text" name="yuqi_check_count_cycle" id="yuqi_check_count_cycle_' + countNum + '"></div>\n      <div class="yuqi_check_count_method_wrap">\u6708\u5185\u6709<input form=\'hidden_form_shaixuan\' type="text" name="yuqi_check_count_method" id="yuqi_check_count_method_' + countNum + '" value=\'\u7D2F\u8BA1\' style="display:none;" readonly></div>\n      <div class="yuqi_check_count_time_wrap"><input form=\'hidden_form_shaixuan\' type="text" name="yuqi_check_count_time" id="yuqi_check_count_time_' + countNum + '"></div>\n      <div class="yuqi_check_count_source_wrap"><input form=\'hidden_form_shaixuan\' type="text" name="yuqi_check_count_source" id="yuqi_check_count_source_' + countNum + '"></div>\n      <div class="click_to_delete" onclick=\'deleteThisFliterLine(this, event)\'>-<img src="' + imgURL + '" alt="u1490"></div>\n    </div>\n    <script>\n      $(\'#yuqi_check_count_cycle_' + countNum + '\').picker({\n        title: "N\u4E2A\u6708",\n        cols: [\n          {\n            textAlign: \'center\',\n            values: window.zhengxinDataArray.yuqiCheckCountCycleArray,\n            displayValues: window.zhengxinDataArray.yuqiCheckCountCycleViewArray\n          }\n        ],\n        onChange: (picker, values, displayValues) => {\n          picker.input.attr(\'inori-data-code\', values[0])\n          setTimeout(()=>{picker.input.val(displayValues[0])}, 0)\n        }\n      })\n      $("#yuqi_check_count_cycle_' + countNum + '").picker("open")\n      $("#yuqi_check_count_cycle_' + countNum + '").picker("close")\n\n      $(\'#yuqi_check_count_time_' + countNum + '\').picker({\n        title: "N\u4E2A",\n        cols: [\n          {\n            textAlign: \'center\',\n            values: window.zhengxinDataArray.yuqiCheckCountTimeArray,\n            displayValues: window.zhengxinDataArray.yuqiCheckCountTimeViewArray\n          }\n        ],\n        onChange: (picker, values, displayValues) => {\n          picker.input.attr(\'inori-data-code\', values[0])\n          setTimeout(()=>{picker.input.val(displayValues[0])}, 0)\n        }\n      })\n      $("#yuqi_check_count_time_' + countNum + '").picker("open")\n      $("#yuqi_check_count_time_' + countNum + '").picker("close")\n\n      $(\'#yuqi_check_count_source_' + countNum + '\').picker({\n        title: "N",\n        cols: [\n          {\n            textAlign: \'center\',\n            values: window.zhengxinDataArray.yuqiCheckCountSourceArray,\n            displayValues: window.zhengxinDataArray.yuqiCheckCountSourceViewArray\n          }\n        ],\n        onChange: (picker, values, displayValues) => {\n          picker.input.attr(\'inori-data-code\', values[0])\n          setTimeout(()=>{picker.input.val(displayValues[0])}, 0)\n        }\n      })\n      $("#yuqi_check_count_source_' + countNum + '").picker("open")\n      $("#yuqi_check_count_source_' + countNum + '").picker("close")\n    </script>\n  ').trim();
  parentEle.closest('.weui_cells').append(templ);
});

// 动态删除条件
function deleteThisFliterLine(_this, evt) {
  $(evt.target).closest('.fliter_line').remove();
}

// 添加渠道至聊天室

function AddPersonToRoom(_this, evt) {
  evt.stopPropagation();
  evt.preventDefault();
  // alert(`building test`)
  // $.toptip(`请先填写客户资料`, 'error')
  // throw new Error(`building`)
  var qudaoID = String($(evt.target).attr('qudao-id'));
  var ajaxIfURL = String($('#chat_ajax_cue').val());
  var ajaxAddURL = String($('#chat_add_chat_group').val());
  var roomID = String($('#chat_person_id').val());
  var goodsID = String($(evt.target).attr('goods-id'));
  var from_user_group_id = sessionStorage.getItem('from_user_group_id');
  if (from_user_group_id === null || from_user_group_id === 'null') {
    var flag = confirm('\u53D1\u8D77\u8054\u7CFB\u524D\u9700\u8981\u5148\u5B8C\u5584\u5BA2\u6237\u8D44\u6599\uFF0C\u662F\u5426\u524D\u5F80\u586B\u5199\uFF1F');
    if (flag) {
      sessionStorage.setItem('qudaoID', qudaoID);
      window.top.postMessage({ jumpTo: 'data' }, '*');
    }

    throw new Error('\u6DFB\u52A0\u6E20\u9053\u5931\u8D25\uFF0C\u4E0D\u5B58\u5728\u804A\u5929\u5BA4');
  }
  var ajaxIfData = {
    chat_id: roomID,
    goods_id: goodsID,
    y_id: qudaoID,
    from_user_group_id: from_user_group_id
  };
  var ajaxAddData = {
    chat_id: roomID,
    goods_id: goodsID,
    y_id: qudaoID
  };
  new Promise(function (resolve, reject) {
    $.ajax(ajaxIfURL, {
      method: 'post',
      data: ajaxIfData,
      beforeSend: function beforeSend() {
        $.toptip('正在查询聊天人员身份', 'success');
      }
    }).fail(function (err) {
      $.toptip('添加渠道时失败', 'error');
      throw err;
    }).done(function (res) {
      if (String(res.code) !== '1') {
        $.toptip('\u9A8C\u8BC1\u6E20\u9053\u8EAB\u4EFD\u5F02\u5E38\uFF0C\u670D\u52A1\u5668\u8FD4\u56DE\uFF1A' + res.message, 'warning');
        console.log('\u9A8C\u8BC1\u6E20\u9053\u8EAB\u4EFD\u5F02\u5E38\uFF0C\u670D\u52A1\u5668\u8FD4\u56DE\uFF1A' + res.message);
        reject(new Error('\u9A8C\u8BC1\u6E20\u9053\u8EAB\u4EFD\u5F02\u5E38\uFF0C\u670D\u52A1\u5668\u8FD4\u56DE\uFF1A' + res.message));
      } else {
        $.toptip('验证渠道身份请求发送成功', 'success');
        console.log('验证渠道身份请求发送成功');
        console.log(res);
        resolve();
      }
    });
  }).then(function (data) {
    return new Promise(function (resolve, reject) {
      $.ajax(ajaxAddURL, {
        method: 'post',
        data: ajaxAddData,
        beforeSend: function beforeSend() {
          $.toptip('正在添加聊天人员。。', 'success');
        }
      }).fail(function (err) {
        $.toptip('添加渠道时失败', 'error');
        reject(err);
        throw err;
      }).done(function (res) {
        if (String(res.code) === '5') {
          $.toptip('渠道人员已经存在', 'warning');
          console.log('渠道人员已经存在');
          $(evt.target).text('正在互动');
          $(evt.target).off('click');
          $(evt.target).on('click', function (evt) {
            $.toptip('\u8BE5\u6E20\u9053\u5DF2\u7ECF\u5728\u7559\u8A00\u677F\u4E86');
          });
          reject(new Error('\u6E20\u9053\u4EBA\u5458\u5DF2\u7ECF\u5B58\u5728'));
        } else if (String(res.code) !== '1') {
          $.toptip('\u670D\u52A1\u5668\u53CD\u5E94\u5F02\u5E38: ' + res.message, 'warning');
          console.log('\u670D\u52A1\u5668\u53CD\u5E94\u5F02\u5E38: ' + res.message);
          reject(new Error('\u670D\u52A1\u5668\u53CD\u5E94\u5F02\u5E38: ' + res.message));
        } else {
          $.toptip('添加渠道请求发送成功', 'success');
          console.log('添加渠道请求发送成功');
          console.log(res);
          resolve();
        }
      });
    });
  }).then(function (data) {
    $.toptip('全部请求完毕', 'success');
    $(evt.target).text('正在互动');
    $(evt.target).removeAttr('onclick');
    $(evt.target).off('click');
    $(evt.target).on('click', function (evt) {
      $.toptip('\u8BE5\u6E20\u9053\u5DF2\u7ECF\u5728\u7559\u8A00\u677F\u4E86', 'warning');
      evt.preventDefault();
    });
    console.log('全部请求完毕');
    // 跳转
    window.top.postMessage({ jumpTo: 'chat' }, '*');
  }).catch(function (err) {
    if (err.message === '验证渠道身份异常，服务器返回：该用户对应该产品已经存在聊天室') {
      $(evt.target).text('正在互动');
      $(evt.target).removeAttr('onclick');
      $(evt.target).off('click');
      $(evt.target).on('click', function (evt) {
        $.toptip('\u8BE5\u6E20\u9053\u5DF2\u7ECF\u5728\u7559\u8A00\u677F\u4E86', 'warning');
        evt.preventDefault();
      });
    } else {
      evt.preventDefault();
    }
  });
}

// 修整渠道人员名字，过长就截取
// 2018年6月6日10点43分 应要求修改为 姓+经理 的格式,仅在按揭员视角显示全称
$('.sub_card_qudao_item .name').each(function (index, item) {
  var anjie = '' + $('#is_anjie').val() === '1';
  if (anjie && $(item).text().length > 4) $(item).text($(item).text().substr(0, 3) + '...');else if (!anjie) $(item).text($(item).text().substr(0, 1) + '\u7ECF\u7406');
});

// 可以取消选择
$('.tag_container label').on('click', function (evt) {
  if ($(evt.target).closest('.tag_container').children('input').prop('checked')) {
    // 已经选上了，要取消选择
    $(evt.target).closest('.tag_container').children('input').prop('checked', false);
    evt.stopPropagation();
    evt.preventDefault();
  }
});